// pages/visitDetail/visitDetail.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    /* 用户信息 */
    userInfo_share:{},
    /*  */
    customerInfo:{
      is_call:'0',
      nickname:'',
      mobile:'',
      visit_name:'',
      visit_count:'',
      avatar:'',
      instime:''
    },
    /*  */
    BorwseLogInfo:{
      page:1,
      pageSize:10,
      userid:'',  //用户id
      visit_userid:''  //被访者id
    },
    /*  */
    shareLogInfo:{
      page:1,
      pageSize:10,
      share_userid:""
    },
    /* 跟进记录参数 */
    clientLogData:{
      client_id:"",  //客户id
      page:"",  //
      pageSize:"", //
      userid:""  // 跟进人id
    },
    /* 页面数据 */
    contentIndex:'0',
    tabContentData:[
      {
        name:'访问分析',
        id:'0',
        emptyWord:'~暂无访问分析记录~',
        showListEmpty:false,
        data:[],   //列表数据
        reqFnName:'getUserBorwseLogInfo',  //获取列表数据方法名
        page:1,  //页码
        pageSize:10, //每页条数
      },
      {
        name:'跟进记录',
        id:'1',
        emptyWord:'~暂无跟进记录~',
        showListEmpty:false,
        data:[],   //列表数据
        reqFnName:'getClientLogs',  //获取列表数据方法名
        page:1,  //页码
        pageSize:10, //每页条数
      },
      {
        name:'关系追踪',
        id:'2',
        emptyWord:'~暂无关系追踪记录~',
        showListEmpty:false,
        data:[],   //列表数据
        reqFnName:'getShareLog',  //获取列表数据方法名
        page:1,  //页码
        pageSize:10, //每页条数
      }
    ],
    /*  */
    clientType:"add",
    clientLogId:"",
    clientLogPop:true,
    clientLogContent:"",
    clientLogContentMax:100,
    /* 调整页面弹层的bottom */
    keyBoardHeight:0,
    /* 客户详情 */
    clientInfo:{},
    matchedClients:{},
    matchedClientsStr:"",
  },
  /* 键盘弹出 */
  keyBoardFocus(e){
    console.log(e);
    this.setData({
      keyBoardHeight:e.detail.height
    });
  },
  /* 键盘收起 */
  keyBoardBlur(){
    this.setData({
      keyBoardHeight:0
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /* 获取客户信息 */
  getClientInfo(client_id){
    return app.globalData.$http.call(this,{
      api:"/getClientInfo",
      data:{
        client_id:client_id
      }
    }).then(res=>{
      console.log(res);
      if(res.data.code=="1"){
        let tmpData = res.data.body;
        //
        let tmpMatchedClients = {};
        let corp_userids = tmpData.corp_userids.split(',');
        let corp_users = tmpData.corp_users.split(',');
        let matchedClientsStr = [];
        corp_userids.forEach((item,i)=>{
          tmpMatchedClients[item] = corp_users[i];
          matchedClientsStr[i] = corp_users[i];
        })
        //
        this.setData({
          matchedClientsStr:matchedClientsStr.join(","),
          matchedClients:tmpMatchedClients,
          clientInfo:tmpData,
          'customerInfo.nickname':tmpData.nickname,
          'customerInfo.mobile':tmpData.mobile,
          'customerInfo.instime':app.globalData.dateFormatYMDHM2(tmpData.instime),
          'customerInfo.visit_count':tmpData.visit_count
        })
        console.log(this.data.matchedClientsStr);
        //console.log(this.data.matchedClients);
        return Promise.resolve();
      }else{
        console.log('sdaosjdoasjdoais');
        return Promise.reject('获取客户详情失败');
      }
    }).catch(err=>{
      console.log(err);
      return Promise.reject('获取客户详情失败');
    })
  },
  /* 确定跟进记录操作 */
  confirmClientLog(){
    if(this.data.clientType==="add"){
      this.insertClientLog();
    }
    if(this.data.clientType==="modify"){
      this.updateClientLog();
    }
  },
  /* 删除跟进记录 */
  deleteClientLog(e){
    let { info } = e.currentTarget.dataset;
    //
    this.setData({
      clientLogId:info.log_id
    });
    wx.showModal({
      title:"提示",
      content:"您将删除当前更进记录，确定是否删除？",
      success:res=>{
        if(res.confirm){
          //
          wx.showLoading({
            title:"删除跟进记录",
            mask:true
          })
          //
          app.globalData.$http.call(this,{
            api:"/deleteClientLog",
            data:{
              log_id:this.data.clientLogId
            }
          }).then(res=>{
            wx.hideLoading();
            console.log(res)
            if(res.data.code=='1'){
              //
              this.pageContentRefresh();
              //
              this.setData({
                clientLogContent:"",
                clientLogPop:true
              });
              return Promise.resolve()
            }else{
              return Promise.reject('删除跟进记录数据失败');
            }
          }).catch(err=>{
            wx.hideLoading();
            //console.log(err);
            return Promise.reject('删除跟进记录数据失败');
          });
        }
      }
    });
  },
  /* 编辑跟进记录 */
  updateClientLog(){
    let args = {
      client_id:this.data.clientLogData.client_id,
      log_id:this.data.clientLogId,
      content:this.data.clientLogContent,
      userid:this.data.userInfo_share.corpUser.userid
    };
    //
    wx.showLoading({
      title:"修改跟进记录",
      mask:true
    })
    //
    app.globalData.$http.call(this,{
      api:"/updateClientLog",
      data:args
    }).then(res=>{
      wx.hideLoading();
      console.log(res)
      if(res.data.code=='1'){
        //
        this.pageContentRefresh();
        //
        this.setData({
          clientLogContent:"",
          clientLogPop:true
        });
        return Promise.resolve()
      }else{
        return Promise.reject('修改跟进记录数据失败');
      }
    }).catch(err=>{
      wx.hideLoading();
      //console.log(err);
      return Promise.reject('修改跟进记录数据失败');
    });
  },
  /* 添加跟进记录 */
  insertClientLog(){
    let args = {
      client_id:this.data.clientLogData.client_id,
      content:this.data.clientLogContent,
      userid:this.data.userInfo_share.corpUser.userid
    };
    //
    wx.showLoading({
      title:"添加跟进记录",
      mask:true
    })
    return app.globalData.$http.call(this,{
      api:"/insertClientLog",
      data:args
    }).then(res=>{
      wx.hideLoading();
      console.log(res)
      if(res.data.code=='1'){
        //
        this.pageContentRefresh();
        //
        this.setData({
          clientLogContent:"",
          clientLogPop:true
        });
        return Promise.resolve()
      }else{
        return Promise.reject('添加跟进记录数据失败');
      }
    }).catch(err=>{
      wx.hideLoading();
      //console.log(err);
      return Promise.reject('添加跟进记录数据失败');
    });
  },
  /* 获取输入的跟进记录 */
  getClientLogContent(e){
    this.setData({
      clientLogContent:e.detail.value
    })
  },
  /* 关闭跟进记录弹层 */
  closeClientPop(){
    this.setData({
      clientLogPop:true
    });
  },
  /* 打开跟进记录弹层--新增 */
  addContentLog(){
    this.setData({
      clientType:"add",
      clientLogContent:"",
      clientLogPop:false
    });
  },
  /* 打开跟进记录弹层--编辑 */
  openClientPop(e){
    let { info } = e.currentTarget.dataset;
    console.log(info);
    this.setData({
      clientType:"modify",
      clientLogId:info.log_id,
      clientLogContent:info.content,
      clientLogPop:false
    });
  },
  /*  */
  addPhoneContact: function(){
    wx.showModal({
      title:"提示",
      content:"请在企业微信员工通道的客户信息页面进行发送短信操作",
      showCancel:false
    });
  },
  /* 打电话 */
  makePhoneCall:function(){
    wx.makePhoneCall({
      phoneNumber: ''+this.data.customerInfo.mobile,
      success:res=>{
        console.log('makePhoneCall');
        //
        app.globalData.fromVDToEmployee = true;
        /* this.updateBrowseOfCall().then(()=>{
          this.setData({
            'customerInfo.is_call':'1'
          })
        }); */
      }
    })
  },
  /* 返回客户管理 */
  goToEmployee:function(){
    wx.navigateBack({
      complete: (res) => {},
    })
  },
  /* 切换数据 */
  changeTabContent:function(e){
    let { index } = e.currentTarget.dataset;
    //console.log(index);
    //
    this.setData({
      contentIndex:index
    });
    //
    /* let tabContentData = this.data.tabContentData;
    tabContentData.forEach(item=>{
      item.showListEmpty = false;
    });
    this.setData({
      tabContentData:tabContentData
    }); */
    //切换显示列表无数据时请求数据
    if(!this.data.tabContentData[this.data.contentIndex*1].data.length){
      this[this.data.tabContentData[this.data.contentIndex*1].reqFnName]&&this[this.data.tabContentData[this.data.contentIndex*1].reqFnName]();
    }
  },
  /* 获取跟进记录数据 */
  getClientLogs(){
    //
    this.setData({
      'clientLogData.page':this.data.tabContentData[this.data.contentIndex*1].page,
      'clientLogData.pageSize':this.data.tabContentData[this.data.contentIndex*1].pageSize
    });
    //
    wx.showLoading({
      title:'',
      mask:true
    });
    //
    return app.globalData.$http.call(this,{
      api:"/getClientLogs",
      data:this.data.clientLogData
    }).then(res=>{
      wx.hideLoading();
      console.log(res)
      if(res.data.code=='1'){
        if(res.data.body.data.length){
          let tmpData = this.data.tabContentData[this.data.contentIndex*1].data;
          let page = this.data.tabContentData[this.data.contentIndex*1].page;
          //
          res.data.body.data.forEach(item=>{
            //
            item.instime = app.globalData.dateFormatYMDHM(item.instime);
            //
            tmpData.push(item);
          });
          page++;
          //
          this.setData({
            [`tabContentData[${this.data.contentIndex*1}].page`]:page,
            [`tabContentData[${this.data.contentIndex*1}].data`]:tmpData,
            [`tabContentData[${this.data.contentIndex*1}].showListEmpty`]:false
          });
        }
        //列表数据为空
        if(!res.data.body.data.length&&!this.data.tabContentData[this.data.contentIndex*1].data.length){
          //
          this.setData({
            [`tabContentData[${this.data.contentIndex*1}].showListEmpty`]:true
          });
        }
        return Promise.resolve()
      }else{
        return Promise.reject('获取跟进记录数据失败');
      }
    }).catch(err=>{
      wx.hideLoading();
      return Promise.reject('获取跟进记录数据失败');
    })
  },
  /* 获取用户浏览信息数据 */
  getUserBorwseLogInfo(){
    //
    this.setData({
      'BorwseLogInfo.page':this.data.tabContentData[this.data.contentIndex*1].page
    });
    //
    wx.showLoading({
      title:'',
      mask:true
    });
    //
    return app.globalData.$http.call(this,{
      api:"/getUserBorwseLogInfo",
      data:this.data.BorwseLogInfo
    }).then(res=>{
      wx.hideLoading();
      console.log(res)
      if(res.data.code=='1'){
        if(res.data.body.data.length){
          let tmpData = this.data.tabContentData[this.data.contentIndex*1].data;
          let page = this.data.tabContentData[this.data.contentIndex*1].page;
          //
          res.data.body.data.forEach(item=>{
            //
            item.insTime = app.globalData.dateFormatYMDHM(item.insTime);
            //
            if(item.type=='0'){
              item.type_value = `${this.data.customerInfo.nickname}进行了${this.data.matchedClients[item.visit_userid]}的${item.type_value}`;
            }
            if(item.type=='1'){
              item.type_value = `${this.data.customerInfo.nickname}查看了${this.data.matchedClients[item.visit_userid]}的${item.type_value}`;
            }
            //
            tmpData.push(item);
          });
          page++;
          //
          this.setData({
            [`tabContentData[${this.data.contentIndex*1}].page`]:page,
            [`tabContentData[${this.data.contentIndex*1}].data`]:tmpData,
            [`tabContentData[${this.data.contentIndex*1}].showListEmpty`]:false
          });
        }
        //列表数据为空
        if(!res.data.body.data.length&&!this.data.tabContentData[this.data.contentIndex*1].data.length){
          //
          this.setData({
            [`tabContentData[${this.data.contentIndex*1}].showListEmpty`]:true
          });
        }
        return Promise.resolve()
      }else{
        return Promise.reject('获取用户浏览记录详情失败');
      }
    }).catch(err=>{
      wx.hideLoading();
      //console.log(err);
      return Promise.reject('获取用户浏览记录详情失败');
    });
  },
  /* 获取追踪记录 */
  getShareLog(){
    //
    this.setData({
      'shareLogInfo.page':this.data.tabContentData[this.data.contentIndex*1].page
    });
    //
    wx.showLoading({
      title:'',
      mask:true
    });
    //
    return app.globalData.$http.call(this,{
      api:"/getShareLog",
      data:this.data.shareLogInfo
    }).then(res=>{
      console.log(res);
      wx.hideLoading();
      if(res.data.code=='1'){
        if(res.data.body.data.length){
          let tmpData = this.data.tabContentData[this.data.contentIndex*1].data;
          let page = this.data.tabContentData[this.data.contentIndex*1].page;
          //
          res.data.body.data.forEach(item=>{
            //
            item.insTime = app.globalData.dateFormatYMDHM2(item.insTime);
            //
            if(item.type=='0'){
              item.relation_str = `${item.insTime} ${item.user_name}通过${item.share_name}的分享访问了${item.visit_name}的名片`;
            }
            if(item.type=='1'){
              item.relation_str = `${item.insTime} ${item.user_name}通过${item.share_name}的分享查看了${item.visit_name}的${item.type_value}`;
            }
            //
            tmpData.push(item);
          });
          page++;
          //
          this.setData({
            [`tabContentData[${this.data.contentIndex*1}].page`]:page,
            [`tabContentData[${this.data.contentIndex*1}].data`]:tmpData,
            [`tabContentData[${this.data.contentIndex*1}].showListEmpty`]:false
          });
        }
        //列表数据为空
        if(!res.data.body.data.length&&!this.data.tabContentData[this.data.contentIndex*1].data.length){
          //
          this.setData({
            [`tabContentData[${this.data.contentIndex*1}].showListEmpty`]:true
          });
        }
        return Promise.resolve()
      }else{
        return Promise.reject('获取用户追踪记录失败');
      }
    }).catch(err=>{
      wx.hideLoading();
      console.log(err);
      return Promise.reject('获取用户追踪记录失败');
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //if(app.globalData.fromVDToEmployee)return;
    // app.globalData.fromVDToEmployee = false;
    //wx.setNavigationBarTitle({title:"客户详情"});
    //获取用户信息
    this.setData({
      userInfo_share:app.globalData.get_userInfo(),
      BorwseLogData:[]
    });
    //
    let eventChannel = this.getOpenerEventChannel();  
    if(app.globalData.fromCustomerManageToVisitDetail){
      app.globalData.fromCustomerManageToVisitDetail = false;
      eventChannel.on('fromCustomerManageToVisitDetail',data=>{
        console.log(data.info);
        //
        this.getClientInfo(data.info.userid).then(()=>{
          //
          this.setData({
            'customerInfo.is_call':data.info.is_call,
            'BorwseLogInfo.userid':data.info.userid,
            'BorwseLogInfo.visit_userid':this.data.userInfo_share.corpUser.userid,
            'customerInfo.avatar':data.info.user_avatar,
            //'customerInfo.instime':app.globalData.dateFormatYMDHM2(data.info.insTime),
            //
            'shareLogInfo.share_userid':data.info.userid,
            //'shareLogInfo.share_userid':this.data.userInfo_share.corpUser.userid
            //
            'clientLogData.client_id':data.info.userid,
            'clientLogData.userid': this.data.userInfo_share.corpUser.userid
          });
          //
          wx.setNavigationBarTitle({
            title: `客户${this.data.customerInfo.nickname}的详情`,
          });
          //切换显示列表无数据时请求数据
          if(!this.data.tabContentData[this.data.contentIndex*1].data.length){
            this[this.data.tabContentData[this.data.contentIndex*1].reqFnName]&&this[this.data.tabContentData[this.data.contentIndex*1].reqFnName]().then(()=>{}).catch(err=>{
              wx.showModal({
                title:'提示',
                content:''+err,
                showCancel:false
              });
            });
          }
        }).catch(err=>{
          wx.showModal({
            title:"提示",
            content:`${err}`,
            showCancel:false
          });
        })
      });
    }
    if(app.globalData.fromEmployeeDetailToVisitDetail){
      app.globalData.fromEmployeeDetailToVisitDetail = false;
      //
      eventChannel.on('fromEmployeeDetailToVisitDetail',data=>{
        console.log(data.info);
        //
        this.getClientInfo(data.info.userid).then(()=>{
          //
          this.setData({
            'customerInfo.is_call':data.info.is_call,
            'BorwseLogInfo.userid':data.info.userid,
            'BorwseLogInfo.visit_userid':this.data.userInfo_share.corpUser.userid,
            'customerInfo.avatar':data.info.user_avatar,
            //'customerInfo.instime':app.globalData.dateFormatYMDHM2(data.info.insTime),
            //
            'shareLogInfo.share_userid':data.info.userid,
            //'shareLogInfo.share_userid':this.data.userInfo_share.corpUser.userid
            //
            'clientLogData.client_id':data.info.userid,
            'clientLogData.userid': this.data.userInfo_share.corpUser.userid
          });
          //
          wx.setNavigationBarTitle({
            title: `客户${this.data.customerInfo.nickname}的详情`,
          });
          //切换显示列表无数据时请求数据
          if(!this.data.tabContentData[this.data.contentIndex*1].data.length){
            this[this.data.tabContentData[this.data.contentIndex*1].reqFnName]&&this[this.data.tabContentData[this.data.contentIndex*1].reqFnName]().then(()=>{}).catch(err=>{
              wx.showModal({
                title:'提示',
                content:''+err,
                showCancel:false
              });
            });
          }
        }).catch(err=>{
          wx.showModal({
            title:"提示",
            content:`${err}`,
            showCancel:false
          });
        })
      });
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.globalData.fromVDToEmployee = true;
  },
  /*  */
  pageContentRefresh(){
    this.setData({
      [`tabContentData[${this.data.contentIndex*1}].page`]:1,
      [`tabContentData[${this.data.contentIndex*1}].data`]:[]
    });
    //
    this[this.data.tabContentData[this.data.contentIndex*1].reqFnName]&&this[this.data.tabContentData[this.data.contentIndex*1].reqFnName]().then(()=>{
      wx.stopPullDownRefresh({
        complete: (res) => {},
      })
    }).catch(err=>{
      wx.stopPullDownRefresh({
        complete: (res) => {},
      })
      wx.showModal({
        title:'提示',
        content:''+err,
        showCancel:false
      });
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.pageContentRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this[this.data.tabContentData[this.data.contentIndex*1].reqFnName]&&this[this.data.tabContentData[this.data.contentIndex*1].reqFnName]().then(()=>{}).catch(err=>{
      wx.showModal({
        title:'提示',
        content:''+err,
        showCancel:false
      });
    });
  }
})